#include <i_string.h>

MISC_DLL_EXPORT std::vector<std::string> SplitString(const std::string& str, const std::string& token)
{
	typedef typename std::string::size_type size_type;
	size_type sl = token.length();
	std::vector<std::string> res;
	size_type pos = 0;
	for (;;)
	{
		size_type newpos = str.find(token, pos);
		if (newpos == str.npos)
		{
			if (pos != str.length())
			{
				res.push_back(str.substr(pos));
			}
			break;
		}
		else
		{
			res.push_back(str.substr(pos, newpos - pos));
		}
		pos = newpos + sl;
	}
	return res;
}

static bool IsSpace(char ch)
{
	return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
}

MISC_DLL_EXPORT std::string& TrimString(std::string& str)
{
	if (str.empty())
		return str;

	do 
	{
		std::string::size_type left = 0;
		while (left < str.length())
		{
			if (!IsSpace(str[left]))
				break;

			++left;
		}

		if (left == str.length())
			break;

		std::string::size_type right = str.length() - 1;
		while (left < right)
		{
			if (!IsSpace(str[right]))
				break;

			--right;
		}

		str = str.substr(left, right - left + 1);
		return str;

	} while (false);
	
	str.clear();
	return str;
}

MISC_DLL_EXPORT std::string& ReplaceCh(std::string& str, char from, char to)
{
	for (auto& ch : str)
	{
		if (ch == from)
			ch = to;
	}

	return str;
}